package com.buddy.sds.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buddy.sds.auth.constant.RoleConstant;
import com.buddy.sds.auth.entity.PermissionTree;
import com.buddy.sds.auth.entity.PermissionTypeEnum;
import com.buddy.sds.auth.entity.SystemPermission;
import com.buddy.sds.auth.entity.SystemUser;
import com.buddy.sds.auth.mapper.ISystemPermissionMapper;
import com.buddy.sds.auth.service.ISystemPermissionService;
import com.buddy.sds.auth.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
@Slf4j
@Primary
@Service
public class SystemPermissionServiceImpl extends ServiceImpl<ISystemPermissionMapper, SystemPermission> implements ISystemPermissionService {


    @Override
    public List<String> getIgnoreUrlList() {

        return baseMapper.getIgnoreUrlList();
    }

    @Override
    public List<SystemPermission> getPermissionListByRole(String role_id) {
        return baseMapper.getPermissionListByRole(role_id);
    }

    @Override
    public List<PermissionTree> getPermissionTreeByUser(String user_id, boolean includeAction) {

        //默认树根节点的pid为ROOT
        return getPermissionTreeByUser(user_id, "ROOT",includeAction);
    }

    @Override
    public List<PermissionTree> getPermissionTree(boolean includeAction) {

        return getPermissionTree("ROOT",includeAction);
    }

    private List<PermissionTree> getPermissionTree(String pid,boolean includeAction){

        List<PermissionTree> permissionTrees = new ArrayList<>();

        List<SystemPermission> permissions = baseMapper.getPermissionListBydPid(pid);




        permissions.forEach(p -> {



            if( ! includeAction){

                if(p.getPermissionType() == PermissionTypeEnum.ACTION || p.getPermissionType() == PermissionTypeEnum.BUTTON ){

                    //如果当前树不包含action级别 直接跳过此节点

                    return;
                }
            }

            PermissionTree permissionTree = new PermissionTree();

            permissionTree.setPermission(p);


            permissionTrees.add(permissionTree);

            if (p.getPermissionType() == PermissionTypeEnum.MENU || p.getPermissionType() == PermissionTypeEnum.FUNCTION) {
                //如果当前是菜单就继续加载子项

                List<PermissionTree> children = getPermissionTree(p.getPermissionId(),includeAction);

                permissionTree.setChildren(children);
            }

        });
        return permissionTrees;

    }

    @Override
    public List<PermissionTree> getPermissionTreeByRole(String role_id) {
        //默认树根节点的pid为ROOT
        return getPermissionTreeByRole(role_id,"ROOT");
    }


    private List<PermissionTree> getPermissionTreeByRole(String role_id,String pid) {

        List<PermissionTree> permissionTrees = new ArrayList<>();

        List<SystemPermission> permissions = baseMapper.getPermissionListByRoleAndPid(role_id,pid);

        permissions.forEach(p -> {

            PermissionTree permissionTree = new PermissionTree();

            permissionTree.setPermission(p);


            permissionTrees.add(permissionTree);

            if (p.getPermissionType() == PermissionTypeEnum.MENU || p.getPermissionType() == PermissionTypeEnum.FUNCTION) {
                //如果当前是菜单就继续加载子项

                List<PermissionTree> children = getPermissionTreeByRole(role_id,p.getPermissionId());

                permissionTree.setChildren(children);
            }

        });
        return permissionTrees;
    }


    @Override
    public Set<String> getPermissionKeyList(String user_id) {

        List<SystemPermission> permissions = baseMapper.getPermissionListByUser(user_id);

        Set<String> result = new HashSet<>();

        permissions.forEach(p->{
            result.add(p.getPermissionKey());
        });

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePermission(String role_id, List<String> permissions, boolean canPlusPermission) {


        //新权限与旧权限对比 重复地方去掉 新权限集合剩余的即为新增 旧权限剩余的即为删除

        List<String> newPermission = new ArrayList<>(permissions);

        List<SystemPermission> oldPermissionList = getPermissionListByRole(role_id);

        Iterator<SystemPermission> it = oldPermissionList.iterator();

        while (it.hasNext()){
            SystemPermission systemPermission = it.next();

            String pid = systemPermission.getPermissionId();

            if(newPermission.contains(pid)){
                //两个集合重复之处 同时减去
                it.remove();
                newPermission.remove(pid);
            }
        }

        //将剩余权限进行处理

        newPermission.forEach(p->{
            String uuid = UUID.randomUUID().toString();
            baseMapper.addRolePermission(uuid,role_id,p);
            log.info("更新权限,新增权限id:{}",p);
        });

        if(canPlusPermission){
            //如果可以减掉权限
            oldPermissionList.forEach(p->{
                baseMapper.deleteRolePermissionByRoleAndPermission(role_id,p.getPermissionId());
                log.info("更新权限,移除权限id:{}",p.getPermissionId());
            });
        }


    }

    @Transactional
    @Override
    public void deleteCascade(String pid) {
        //删除子节点
        List<SystemPermission> permissions = baseMapper.getPermissionListBydPid(pid);

        permissions.forEach(p->{
            deleteCascade(p.getPermissionId());
        });
        baseMapper.deleteById(pid);
        //删除角色关联表信息
        this.baseMapper.deleteRolePermissionByPermission(pid);


        log.info("删除角色 id:{} ",pid);
    }

    @Override
    public boolean toggleVisible(String pid) {

        SystemPermission systemPermission = baseMapper.selectById(pid);

        if(systemPermission == null){
            return false;
        }

        return baseMapper.toggleVisible(pid, !systemPermission.isPermissionVisible());
    }

    @Override
    public boolean toggleAuth(String pid) {

        SystemPermission systemPermission = baseMapper.selectById(pid);

        if(systemPermission == null){
            return false;
        }

        return baseMapper.toggleIgnore(pid, !systemPermission.isPermissionIgnore());
    }

    @Override
    public void removeHomePage() {
        baseMapper.disableHomePage();
    }

    @Override
    public String getHomePagePath() {

        return baseMapper.getHomePagePath();

    }


    private List<PermissionTree> getPermissionTreeByUser(String user_id, String pid, boolean includeAction) {

        List<PermissionTree> permissionTrees = new ArrayList<>();

        List<SystemPermission> permissions = baseMapper.getPermissionListByUserAndPid(user_id, pid);


        boolean hasAdminRole = AuthUtil.hasRole(RoleConstant.ADMIN_ROLE_IDENTIFIER);

        permissions.forEach(p -> {

            if(hasAdminRole){
                //管理员需要看见所有菜单，不然就麻烦啦!!!
                p.setPermissionVisible(true);
            }

            if( ! includeAction){

                if(p.getPermissionType() == PermissionTypeEnum.ACTION || p.getPermissionType() == PermissionTypeEnum.BUTTON ){

                    //如果当前树不包含action级别 直接跳过此节点

                    return;
                }
            }

            PermissionTree permissionTree = new PermissionTree();

            permissionTree.setPermission(p);


            permissionTrees.add(permissionTree);

            if (p.getPermissionType() == PermissionTypeEnum.MENU || p.getPermissionType() == PermissionTypeEnum.FUNCTION) {
                //如果当前是菜单就继续加载子项

                List<PermissionTree> children = getPermissionTreeByUser(user_id,p.getPermissionId(),includeAction);

                permissionTree.setChildren(children);
            }

        });
        return permissionTrees;
    }


}
